<?php
/**
 * CustomerDataGridView
 *
 * @version    1.0
 * @package    samples
 * @subpackage tutor
 * @author     Pablo Dall'Oglio
 * @copyright  Copyright (c) 2006-2011 Adianti Solutions Ltd. (http://www.adianti.com.br)
 * @license    http://www.adianti.com.br/framework-license
 */
class CustomerDataGridView extends TPage
{
    private $form;      // search form
    private $datagrid;  // listing
    private $pageNavigation;
    private $loaded;
    
    /**
     * Class constructor
     * Creates the page, the search form and the listing
     */
    public function __construct()
    {
        parent::__construct();
        new TSession;
        
        // creates the form
        $this->form = new TQuickForm('form_search_customer');
        
        // create the form fields
        $name   = new TEntry('name');
        $name->setValue(TSession::getValue('customer_name'));
        
        // add the form fields
        $this->form->addQuickField('name', $name,  100);

        // define the form action
        $this->form->addQuickAction('Find', new TAction(array($this, 'onSearch')), 'ico_find.png');
        $this->form->addQuickAction('New',  new TAction(array('CustomerFormView', 'onEdit')), 'ico_new.png');

        // creates a DataGrid
        $this->datagrid = new TQuickGrid;
        $this->datagrid->setHeight(230);

        // creates the datagrid columns
        $this->datagrid->addQuickColumn('Id', 'id', 'right', 40, new TAction(array($this, 'onReload')), array('order', 'id'));
        $this->datagrid->addQuickColumn('Name', 'name', 'left', 170, new TAction(array($this, 'onReload')), array('order', 'name'));
        $this->datagrid->addQuickColumn('Address', 'address', 'left', 170);
        $this->datagrid->addQuickColumn('City', 'city_name', 'left', 140);

        // creates two datagrid actions
        $this->datagrid->addQuickAction('Edit', new TDataGridAction(array('CustomerFormView', 'onEdit')), 'id', 'ico_edit.png');
        $this->datagrid->addQuickAction('Delete', new TDataGridAction(array($this, 'onDelete')), 'id', 'ico_delete.png');
        
        // create the datagrid model
        $this->datagrid->createModel();
        
        // creates the page navigation
        $this->pageNavigation = new TPageNavigation;
        $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
        $this->pageNavigation->setWidth($this->datagrid->getWidth());
        
        // creates the page structure using a table
        $table = new TTable;
        $table->addRow()->addCell($this->form);
        $table->addRow()->addCell($this->datagrid);
        $table->addRow()->addCell($this->pageNavigation);
        // add the table inside the page
        parent::add($table);
    }
    
    /**
     * method onSearch()
     * Register the filter in the session when the user performs a search
     */
    function onSearch()
    {
        // get the search form data
        $data = $this->form->getData();
        
        // check if the user has filled the form
        if (isset($data->name))
        {
            // creates a filter using what the user has typed
            $filter = new TFilter('name', 'like', "%{$data->name}%");
            
            // stores the filter in the session
            TSession::setValue('customer_filter', $filter);
            TSession::setValue('customer_name',   $data->name);
            
            // fill the form with data again
            $this->form->setData($data);
        }
        
        $param=array();
        $param['offset']    =0;
        $param['first_page']=1;
        $this->onReload($param);
    }
    
    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param = NULL)
    {
        try
        {
            // open a transaction with database 'samples'
            TTransaction::open('samples');
            
            // creates a repository for Customer
            $repository = new TRepository('Customer');
            $limit = 05;
            
            // creates a criteria
            $criteria = new TCriteria;
            $criteria->setProperties($param); // order, offset
            $criteria->setProperty('limit', $limit);
            
            if (TSession::getValue('customer_filter'))
            {
                // add the filter stored in the session to the criteria
                $criteria->add(TSession::getValue('customer_filter'));
            }
            
            // load the objects according to criteria
            $customer = $repository->load($criteria);
            $this->datagrid->clear();
            if ($customer)
            {
                foreach ($customer as $customer)
                {
                    // add the object inside the datagrid
                    $this->datagrid->addItem($customer);
                }
            }
            
            // reset the criteria for record count
            $criteria->resetProperties();
            $count= $repository->count($criteria);
            
            $this->pageNavigation->setCount($count); // count of records
            $this->pageNavigation->setProperties($param); // order, page
            $this->pageNavigation->setLimit($limit); // limit
            
            // close the transaction
            TTransaction::close();
            $this->loaded = true;
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', '<b>Error</b> ' . $e->getMessage());
            // undo all pending operations
            TTransaction::rollback();
        }
    }
    
    /**
     * method onDelete()
     * executed whenever the user clicks at the delete button
     * Ask if the user really wants to delete the record
     */
    function onDelete($param)
    {
        // get the parameter $key
        $key=$param['key'];
        
        // define two actions
        $action1 = new TAction(array($this, 'Delete'));
        
        // define the action parameters
        $action1->setParameter('key', $key);
        
        // shows a dialog to the user
        new TQuestion('Do you really want to delete ?', $action1);
    }
    
    /**
     * method Delete()
     * Delete a record
     */
    function Delete($param)
    {
        try
        {
            // get the parameter $key
            $key=$param['key'];
            
            // open a transaction with database 'samples'
            TTransaction::open('samples');
            
            // instantiates object Customer
            $customer = new Customer($key);
            // deletes the object from the database
            $customer->delete();
            
            // close the transaction
            TTransaction::close();
            
            // reload the listing
            $this->onReload();
            // shows the success message
            new TMessage('info', "Record Deleted");
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', '<b>Error</b> ' . $e->getMessage());
            // undo all pending operations
            TTransaction::rollback();
        }
    }

    /**
     * method show()
     * Shows the page
     */
    function show()
    {
        // check if the datagrid is already loaded
        if (!$this->loaded)
        {
            $this->onReload();
        }
        parent::show();
    }
}
?>